﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections;

namespace Core
{
    public class ImmutableUtil
    {
        public static bool? NullCheck(object o1, object o2)
        {
            if (o1 == null || o2 == null)
                return (o1 == null && o2 == null);
            return null;
        }

        public static bool DSEquals<V>(V left, V right)
        {
            if (left == null || right == null)
                return left == null && right == null;

            var len = left as IEnumerable;
            var ren = right as IEnumerable;

            if (len == null && ren == null)
                return left.Equals(right);

            if (len == null || ren == null)
                return false;

            return SequenceEqual(len, ren);
        }

        public static bool SequenceEqual(IEnumerable en1, IEnumerable en2)
        {
            var enumerator = en2.GetEnumerator();
            foreach (var o in en1)
            {
                if (!enumerator.MoveNext())
                    return false;

                if (!DSEquals(o, enumerator.Current))
                    return false;
            }

            return !enumerator.MoveNext();
        }

        public static bool ArrayEquals<T>(T[] a1, T[] a2)
        {
            if (a1.Length != a2.Length)
                return false;

            for (var i = 0; i < a1.Length; i++)
                if (!DSEquals(a1[i], a2[i]))
                    return false;

            return true;
        }

        internal static int ArrayHash<T>(T[] Array)
        {
            var Hash = 0;
            foreach (var o in Array) if (o != null) Hash ^= o.GetHashCode();
            return Hash;
        }
    }
}